<?php
	class UserModel extends CI_Model
	{
		public function __construct()
		{
			$this->load->database();
		}
		public final function addUser($user)
		{
			$n = $user;
			$a = array
			(
				'FullName' => $n->FullName,
				'Username' => $n->Username,
				'Email' => $n->Email,
				'Password' => md5($n->Password),
				'Mobile' => $n->Mobile,
				'Landline' => $n->Landline
			);
			$this->db->insert('users', $a);
		}
		public final function getAllUsers()
		{
			$q = $this->db->get('users');
			return $q->result_object();
		}
		public final function getUserById($id)
		{
			$q = $this->db->get_where('users', array('Id' => $id));
			return $q->result_object();
		}
		public final function getUserByUsername($username)
		{
			$q = $this->db->get_where('users', array('Username' => $username));
			return $q->result_object();
		}
		public final function getUserByLoginCredential($username, $password)
		{
			$q = $this->db->get_where('ngos', array('Username' => $username, 'Password' => $password));
			return $q->result_object();
		}
		public final function updateUser($user)
		{
			$n = $user;
			$a = array
			(
				'FullName' => $n->FullName,
				'Username' => $n->Username,
				'Email' => $n->Email,
				'Mobile' => $n->Mobile,
				'Landline' => $n->Landline
			);
			$this->db->where('Id', $n->Id);
			$this->db->update('users', $a);
		}
		public final function resetPassword()
		{
			$p = $this->input->post;
			if($p('id') AND $p('token'))
			{
				$this->db->where('Id', $p('id'));
				$this->db->where('PasswordResetToken', $p('token'));
				$a = array('Password' => md5($p('newPassword')));
				$this->db->update('users', $a);
			}
		}
		public final function getIsValidToken($userId, $token)
		{
			$this->db->where('Id', $userId);
			$this->db->where('ResetPasswordFlag', TRUE);
			$this->db->where('ResetPasswordToken', $token);
			$this->db->from('Users');
			return $this->db->count_all_results() > 0;
		}
		public final function updateResetPasswordFlag($username, $enabled = false)
		{
			$this->db->where('Username', $username);
			$a = array('ResetPasswordFlag' => $enabled);
			if($enabled == true)
			{
				$s = random_string('alnum', 16);
				$a['PasswordResetToken'] = $this->encrypt->encode($s);
			}
			$this->db->update('users', $a);
		}
		public final function updatePassword($id, $newPassword)
		{
			$this->db->where('Id', $n->Id);
			$this->db->update('users', array('Password' => md5($newPassword)));
		}
		public final function removeUserById($id)
		{
			$q = $this->db->delete('user', array('Id', $id));
			return $q->result_object();
		}
	}